/**
 *
 */
package ms.platform.progress.service;

import ms.platform.plan.model.ModelPlan;
import ms.platform.plan.model.ModelProcessPlan;
import ms.platform.progress.dao.FactoryPlanDao;
import ms.platform.progress.dao.IndexAuditDao;
import ms.platform.progress.dao.ProgressViewDao;
import ms.platform.progress.dto.*;
import ms.platform.progress.model.AuditResult;
import ms.platform.util.DateUtil;
import ms.platform.util.PageUtils;
import ms.platform.util.StringUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 进度查看Service
 *
 * @author Kevin Deng
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class ProgressViewService implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -5935922036966149526L;

    @Autowired
    private ProgressViewDao progressViewDao;
    @Autowired
    private FactoryPlanDao factoryPlanDao;
    @Autowired
    private IndexAuditDao indexAuditDao;
    @Autowired
    FactoryPlanService factoryService;

    public List<ProgressViewVo> viewProgress(Map<String, Object> map) {
        List<ProgressRecordVo> progressRecordVos = progressViewDao.findProcessRecordByConditions(map);
        List<ProgressViewVo> progressViewVos = new ArrayList<>();
        if (progressRecordVos != null && progressRecordVos.size() > 0) {
            Integer lastModelId = 0; //定义上一个modelId 因为在查询列表时已经按照modelId以及recorddate排序
            Integer currentModelId = null; //定义一个变量保存当前循环到的modelId
            ProgressViewVo currentProgressViewVo = null; //定义一个变量保存当前ProgressViewVo
            Date startDate = DateUtil.convertStringToDate(map.get("startDate").toString(), "yyyy-MM-dd");
            Date endDate = DateUtil.convertStringToDate(map.get("endDate").toString(), "yyyy-MM-dd");
            int i = 0;
            for (ProgressRecordVo progressRecordVo : progressRecordVos) {
                currentModelId = progressRecordVo.getModelId(); //复制循环的获取的currentModelId
                if (lastModelId.intValue() != currentModelId.intValue()) { //与上一个modelId做比较,假如不相等则表明已跳转到下一个model的数据
                    if (currentProgressViewVo != null) {
                        //初始化没有的日历
                        initDefaultItem(currentProgressViewVo, startDate, endDate);
                        //排序items使在页面按时间从前到晚显示
                        sortList(currentProgressViewVo.getItems());
                    }
                    //假如是已跳到下一个model的数据则new一个新的VO对象
                    currentProgressViewVo = new ProgressViewVo();
                    currentProgressViewVo.setFactory(progressRecordVo.getFactory());
                    currentProgressViewVo.setModelLevel(progressRecordVo.getModelLevel());
                    currentProgressViewVo.setModelNo(progressRecordVo.getModelCode());
                    currentProgressViewVo.setEngineering(progressRecordVo.getEngineering());
                    currentProgressViewVo.setActualDays(progressRecordVo.getActualDays());
                    progressViewVos.add(currentProgressViewVo);
                    lastModelId = currentModelId;
                }
                ProgressViewItemVo item = new ProgressViewItemVo();
                item.setDate(DateUtil.getDateString(progressRecordVo.getRecordDate(), "MM-dd"));
                item.setReportDate(DateUtil.getDateString(progressRecordVo.getRecordDate(), "yyyy-MM-dd"));
                item.setRecordStatus(progressRecordVo.getStatus());
                item.setStatus(progressRecordVo.getProgressStatus());
                item.setDays(progressRecordVo.getDelayDays());
                item.setProgress(progressRecordVo.getModelProcessName());
                currentProgressViewVo.getItems().add(item);
                if (++i == progressRecordVos.size()) {
                    //初始化最后一个model的数据
                    //初始化没有的日历
                    initDefaultItem(currentProgressViewVo, startDate, endDate);
                    //排序items使在页面按时间从前到晚显示
                    sortList(currentProgressViewVo.getItems());
                }
            }
        }
        return progressViewVos;
    }

    /**
     * progressViewItem List 排序方法
     *
     * @param items
     */
    private void sortList(List<ProgressViewItemVo> items) {
        Collections.sort(items, new Comparator<ProgressViewItemVo>() {

            @Override
            public int compare(ProgressViewItemVo o1, ProgressViewItemVo o2) {
                return o1.getDate().compareTo(o2.getDate());
            }

        });
    }

    /**
     * 初始化数据库中没有提交台帐的日历报告
     *
     * @param pvv
     * @param startDate
     * @param endDate
     */
    private void initDefaultItem(ProgressViewVo pvv, Date startDate, Date endDate) {
        Date d = new Date(startDate.getTime());
        long longEndDate = endDate.getTime();
        while (d.getTime() < longEndDate) {
            ProgressViewItemVo pviv = new ProgressViewItemVo();
            pviv.setDate(DateUtil.getDateString(d, "MM-dd"));
            if (!pvv.getItems().contains(pviv)) {
                pvv.getItems().add(pviv);
            }
            d = DateUtil.addDate(d, 1);
        }
    }

    public ProgressViewDao getProgressViewDao() {
        return progressViewDao;
    }

    public void setProgressViewDao(ProgressViewDao progressViewDao) {
        this.progressViewDao = progressViewDao;
    }

    public List<ProgressAccountDto> queryProgessAccount(Map<String, Object> map) {
        return progressViewDao.queryProgessAccount(map);
    }

    /**
     * 根据计划台账id查询台账明细
     *
     * @return
     */
    public ProgressDetailDto getProgressDetailById(String recordId, String recordDetailId) {
        ProgressDto progressDto = new ProgressDto();
        ProgressDetailDto detailDto = new ProgressDetailDto();
        AuditResult auditResult = new AuditResult();
        if (null != recordId) {
            progressDto = factoryPlanDao.getProgressRecordById(Integer.parseInt(recordId));
            if (null != progressDto.getRecordDetailId()) {
                detailDto = factoryPlanDao.getProgressRecordDetailById(Integer.parseInt(recordDetailId));
                if (null != detailDto) {
                    detailDto.setModelCode(progressDto.getModelCode());
                    if (null != detailDto.getReviewRcdId()) {
                        auditResult = indexAuditDao.getAduitResult(detailDto.getReviewRcdId());
                    }
                }
            }
        }
        if (null != progressDto.getModelPlanId()) {
            //检查是否 是 计划结束 后
            ModelPlan modelPlan = factoryService.getmodelPlan(progressDto.getModelPlanId());//获取结束时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String endDate = sdf.format(modelPlan.getPlanEndTime());
            String newDate = sdf.format(new Date());
            //判断当前时间是否大于计划结束时间
            //如果大于，计划比例为100
            boolean lastTemp = false;
            if (DateUtil.middate(newDate, endDate, sdf) >= 0) {
                lastTemp = true;
            }
            ProgressDto dto;
            dto = this.queryModelProcessByPlanId(progressDto.getModelPlanId(),lastTemp);
            if (null != detailDto) {
                detailDto.setModelPlanId(progressDto.getModelPlanId());
                detailDto.setEngineering(progressDto.getEngineering());
                detailDto.setPlanProgress(progressDto.getPlanProcessName() == null ? dto.getPlanProgress() : progressDto.getPlanProcessName());//计划进度
                detailDto.setPlanPro(dto.getPlanPro());//计划完成比例
                detailDto.setTargetPre(dto.getTargetPre());
                detailDto.setModelProcessId(dto.getModelProcessId());
                detailDto.setReportDate(progressDto.getReportDate());
                detailDto.setCurrentPro(progressDto.getCurrentPro() == null ? dto.getCurrentPro() : progressDto.getCurrentPro());//当前进度
                if ("3".equals(auditResult.getResult())) {
                    detailDto.setStatus("已拒绝");
                } else if (null != auditResult.getRevirwUser() && auditResult.getResult().equals("1")) {
                    detailDto.setStatus("已完成");
                } else {
                    detailDto.setStatus("待二审");
                }

                detailDto.setAdvise(auditResult.getReviewAdvise() == null ? auditResult.getAdvise() : auditResult.getReviewAdvise());
            }
        }
        return detailDto;
    }

    /**
     * 获取工序信息
     *
     * @param id
     * @return
     */
    public ProgressDto queryModelProcessByPlanId(Integer id, boolean lastTemp) {
        ProgressDto proDto = new ProgressDto();
        Date reportDate = DateUtil.getNowDate();
        proDto.setModelPlanId(id);
        proDto.setReportDate(DateUtil.getDateString(reportDate, "yyyy-MM-dd"));
        List<ModelProcessPlan> processList = factoryPlanDao.queryModelProcessByPlanId(id);
        int processSize = processList.size();
        int proTemp = 1;
        for (ModelProcessPlan modelProcessPlan : processList) {
            boolean flag = DateUtil.isEffectiveDate(reportDate, modelProcessPlan.getPlanStartTime(), modelProcessPlan.getPlanEndTime());
            //如果是计划后的时间,取最后一个工序
            if(lastTemp && (processSize == proTemp)){
                flag = true;
            }
            if (flag) {
                long day = DateUtil.getDayByDateSubraction(reportDate, modelProcessPlan.getPlanStartTime());
                proDto.setModelCode(modelProcessPlan.getModelCode());
                proDto.setPlanProgress(modelProcessPlan.getProcessName());

                if (day == 0) {
                    proDto.setPlanPro(Math.floor(100 / modelProcessPlan.getPlanTotalTime() * 1) + "");
                } else {
                    proDto.setPlanPro(Math.floor(100 / modelProcessPlan.getPlanTotalTime() * day) + "");
                }
                proDto.setTargetPre(modelProcessPlan.getTargetPre());
                ModelProcessPlan currentProgress = factoryPlanDao.queryCurrentProgress(id);
                if (null != currentProgress && StringUtils.isNotEmpty(currentProgress.getProcessName())) {
                    proDto.setCurrentPro(currentProgress.getProcessName());
                    proDto.setModelProcessId(currentProgress.getId());
                } else {
                    ModelProcessPlan currentProgressTwo = factoryPlanDao.queryCurrentProgressTwo(id);
                    proDto.setCurrentPro(currentProgressTwo.getProcessName());
                    proDto.setModelProcessId(currentProgressTwo.getId());
                }
                break;
            }
            proTemp++;
        }
        return proDto;
    }

    /**
     * 大屏展示
     *
     * @param map
     * @return
     */
    public List<ProgressViewVo> showLargeScreen(Map<String, Object> map) {
        List<ProgressRecordVo> progressRecordVos = progressViewDao.showLargeScreen(map);
        List<ProgressViewVo> progressViewVos = new ArrayList<>();
        if (progressRecordVos != null && progressRecordVos.size() > 0) {
            Integer lastModelId = 0; //定义上一个modelId 因为在查询列表时已经按照modelId以及recorddate排序
            Integer currentModelId = null; //定义一个变量保存当前循环到的modelId
            ProgressViewVo currentProgressViewVo = null; //定义一个变量保存当前ProgressViewVo
            Date startDate = DateUtil.convertStringToDate(map.get("startDate").toString(), "yyyy-MM-dd");
            Date endDate = DateUtil.convertStringToDate(map.get("endDate").toString(), "yyyy-MM-dd");
            int i = 0;
            for (ProgressRecordVo progressRecordVo : progressRecordVos) {
                currentModelId = progressRecordVo.getModelId(); //复制循环的获取的currentModelId
                if (lastModelId.intValue() != currentModelId.intValue()) { //与上一个modelId做比较,假如不相等则表明已跳转到下一个model的数据
                    if (currentProgressViewVo != null) {
                        //初始化没有的日历
                        initDefaultItem(currentProgressViewVo, startDate, endDate);
                        //排序items使在页面按时间从前到晚显示
                        sortList(currentProgressViewVo.getItems());
                    }
                    //假如是已跳到下一个model的数据则new一个新的VO对象
                    currentProgressViewVo = new ProgressViewVo();
                    currentProgressViewVo.setFactory(progressRecordVo.getFactory());
                    currentProgressViewVo.setModelLevel(progressRecordVo.getModelLevel());
                    currentProgressViewVo.setModelNo(progressRecordVo.getModelCode());
                    currentProgressViewVo.setEngineering(progressRecordVo.getEngineering());
                    currentProgressViewVo.setActualDays(progressRecordVo.getActualDays());
                    if (null != progressRecordVo.getPlanId()) {
                        currentProgressViewVo.setPlanId(progressRecordVo.getPlanId().toString());
                    }
                    progressViewVos.add(currentProgressViewVo);
                    lastModelId = currentModelId;
                }
                ProgressViewItemVo item = new ProgressViewItemVo();
                item.setDate(DateUtil.getDateString(progressRecordVo.getRecordDate(), "MM-dd"));
                item.setReportDate(DateUtil.getDateString(progressRecordVo.getRecordDate(), "yyyy-MM-dd"));
                item.setRecordStatus(progressRecordVo.getStatus());
                item.setDays(progressRecordVo.getDelayDays());
                item.setProgress(progressRecordVo.getModelProcessName());
                currentProgressViewVo.getItems().add(item);
                if (++i == progressRecordVos.size()) {
                    //初始化最后一个model的数据
                    //初始化没有的日历
                    initDefaultItem(currentProgressViewVo, startDate, endDate);
                    //排序items使在页面按时间从前到晚显示
                    sortList(currentProgressViewVo.getItems());
                }
            }
        }
        return progressViewVos;
    }

    public List<ModelPlanDto> queryAllModelPlan(Map<String, Object> map, HttpServletRequest request){
        Date startDate = DateUtil.convertStringToDate(map.get("startDate").toString(), "yyyy-MM-dd");
        Date endDate = DateUtil.convertStringToDate(map.get("endDate").toString(), "yyyy-MM-dd");
        map.put("count", progressViewDao.queryAllModelPlanCount(map));
        List<ModelPlanDto> list = progressViewDao.queryAllModelPlan(PageUtils.Page(request, map));
        for (ModelPlanDto modelPlanDto : list) {
            map.put("modelPlanId", modelPlanDto.getModelPlanId());
            List<ProgressRecordVo> prvDto = progressViewDao.queryProgessRecord(map);
            List<ProgressViewItemVo> pvvList = new ArrayList<>();
            List<ModelProcessPlan> process = new ArrayList<>();
            if (null != prvDto && prvDto.size() > 0) {
                process = factoryPlanDao.queryModelProcessByPlanId(prvDto.get(0).getPlanId());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String newDate = df.format(new Date());
            boolean tempLastTime = false;
            ModelPlan modelPlan = factoryService.getmodelPlan(modelPlanDto.getModelPlanId());//获取结束时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            for (ProgressRecordVo progressRecordVo : prvDto) {

                String modelPlanEndDate = sdf.format(modelPlan.getPlanEndTime());
                String modelPlanNewDate = sdf.format(new Date());

                //判断当前时间是否大于计划结束时间
                //如果大于，则沿用计划结束最后天来提交进度
                boolean tempTime = false;
                boolean isShenhe = false;
                if (DateUtil.middate(modelPlanEndDate, modelPlanNewDate, sdf) < 0) {
                    isShenhe = true;
                    tempTime = true;
                    tempLastTime = true;
                }

                //获取比例 及阶段
                ProgressDetailDto detailDto = factoryService.getProgressDetailById(Integer.parseInt(progressRecordVo.getRecordId()), true, tempTime, isShenhe);
                ProgressViewItemVo item = new ProgressViewItemVo();
                //从提交日开始,前面都不显示 显示大于提交期
                item.setReceiveFlag("0");
                if (modelPlan.getAccDate() != null) {
                    if (DateUtil.middate(df.format(modelPlan.getAccDate()), df.format(progressRecordVo.getRecordDate()), df) < 0) {
                        item.setReceiveFlag(modelPlan.getReceiveFlag());//当厂家 从来未提交过任务时,为0 不显示实际比例等
                    }
                }

                //判断是否提交进度,为0时是提交
                String lastTime = "";
                if (DateUtil.middate(newDate, df.format(progressRecordVo.getRecordDate()), sdf) == 0) {
                    if (!StringUtil.isNullOrBlock(modelPlan.getLastReportTime())) {
                        lastTime = sdf.format(modelPlan.getLastReportTime());//最后一次提交记录
                        item.setLastTime(Long.valueOf(DateUtil.middate(newDate, lastTime, sdf)).toString());
                    }
                }
                item.setPlanProgress(detailDto.getPlanProgress());//计划进度
                //计划完成 过期 计划比例为100
                if (tempTime) {
                    item.setProgress(detailDto.getPlanProgress());
                    detailDto.setPlanPro("100");
                    item.setStamp("isDelay");//标记是否计划后 如果是 沿用就显示 出货➕100%
                }
                //为空false
                if (StringUtils.isNotBlank(detailDto.getPlanPro())) {
                	try{
                		item.setPlanPro(Integer.valueOf(detailDto.getPlanPro()) > 100 ? "100" : detailDto.getPlanPro());//计划完成比例
                	}catch(Exception e){
                		item.setPlanPro("0");
                	}
                }
                item.setCurrentPro(detailDto.getCurrentPro());//当前进度
                item.setAccPro(detailDto.getAccPro());//实际完成比例
                item.setAccPre(detailDto.getAccPre());	
                for (ModelProcessPlan modelProcessPlan : process) {
                	if(!"GO2".equals(modelProcessPlan.getProcessName())){
                		boolean flag = DateUtil.isEffectiveDate(progressRecordVo.getRecordDate(), modelProcessPlan.getPlanStartTime(), modelProcessPlan.getPlanEndTime());
                        if (flag) {
                            item.setProgress(modelProcessPlan.getProcessName());
//                            break;
                        }
                	}
                }
                if (!"0".equals(progressRecordVo.getProgressStatus()) && !StringUtils.isEmpty(progressRecordVo.getProgressStatus())) {
                    item.setDays(progressRecordVo.getDelayDays());
                    item.setRecordStatus(progressRecordVo.getProgressStatus());
                } else {
                    int res = DateUtil.compare_date(DateUtil.getDateString(progressRecordVo.getRecordDate(), "yyyy-MM-dd"), DateUtil.getDateString(DateUtil.getNowDate(), "yyyy-MM-dd"));
                    if (res != 1) {
                        Map<String, Object> mapn = new HashMap<String, Object>();
                        mapn.put("modelPlanId", modelPlanDto.getModelPlanId());
                        mapn.put("recordDate", DateUtil.getDateString(progressRecordVo.getRecordDate(), "yyyy-MM-dd"));
                        //ProgressRecordVo pv = progressViewDao.queryIsSubmitRecord(mapn);
                        String rDate = DateUtil.getDateString(progressRecordVo.getRecordDate(), "yyyy-MM-dd");
                        int week = DateUtil.dayForWeek(rDate);
                       for (int i = 0; i < prvDto.size(); i++) {
                    	   if(week !=2 && week != 5){
                           	if(week == 1){
                           		rDate = DateUtil.getPreviousDate(DateUtil.convertStringToDate(rDate, "yyyy-MM-dd"), 3, "yyyy-MM-dd");
                           		mapn.put("recordDate", rDate);
                           	}else if(week == 7 || week == 4){
                           		rDate = DateUtil.getPreviousDate(DateUtil.convertStringToDate(rDate, "yyyy-MM-dd"), 2, "yyyy-MM-dd");
                           		mapn.put("recordDate", rDate);
                           	}else{
                           		rDate = DateUtil.getPreviousDate(DateUtil.convertStringToDate(rDate, "yyyy-MM-dd"), 1, "yyyy-MM-dd");
                           		mapn.put("recordDate", rDate);
                           	}
                        	ProgressRecordVo pvss = progressViewDao.queryIsSubmitRecord(mapn);
                        	if(pvss != null){
                        		if(detailDto.getPlanProgress().equals(pvss.getPlanProcessName())){//判断是否是在同一个工序，如果不在则不能沿用上一次的进度
                            		Map<String, String> maps = new HashMap<String, String>();
                            		maps.put("modelPlanId", detailDto.getModelPlanId().toString());
                        			maps.put("currentPro", detailDto.getPlanProgress());
                        			ProgressDto dto = factoryService.getPlanStartTimeByProcessNameTwo(maps);
                        			long day = DateUtil.getDayByDateSubraction(DateUtil.convertStringToDate(detailDto.getReportDate(), "yyyy-MM-dd"),dto.getPlanStartTime());
                            		ModelPlan modelPlans = factoryService.getmodelPlan(detailDto.getModelPlanId());//获取结束时间
                        			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                        			String endDate1 = sdf1.format(modelPlans.getPlanEndTime());
                        			String newDate1 = sdf1.format(new Date());
                            		
                            		item.setDays(pvss.getDelayDays());
                                    item.setRecordStatus(pvss.getProgressStatus());
                                    item.setCurrentPro(pvss.getCurrentPro());//当前进度
                                    item.setAccPro(pvss.getAccPro());//实际完成比例
                                    item.setAccPre(pvss.getAccPre());
                                  //判断当前时间是否大于计划结束时间
                        			//如果大于，计划比例为100
                        			if (DateUtil.middate(newDate1, endDate1, sdf1) >= 0) {
                        				item.setPlanPro("100");
                        			}else{
                        				DecimalFormat df1 = new DecimalFormat("#");
                        				item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));//计划完成比例
                        				if(100/(double)dto.getPlanTotalTime()*day<=100){
                        					item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));
                        				}else{
                        					item.setPlanPro("100");
                        				}
                        			}
                                    break;
                            	}else{
                            		item.setDays(pvss.getDelayDays());
                                    item.setRecordStatus(pvss.getProgressStatus());
                                    item.setCurrentPro(pvss.getCurrentPro());//当前进度
                                    item.setAccPro(pvss.getAccPro());//实际完成比例
                            		Map<String, String> maps = new HashMap<String, String>();
                            		maps.put("modelPlanId", detailDto.getModelPlanId().toString());
                        			maps.put("currentPro", detailDto.getPlanProgress());
                        			ProgressDto dto = factoryService.getPlanStartTimeByProcessNameTwo(maps);
                        			long day = DateUtil.getDayByDateSubraction(DateUtil.convertStringToDate(detailDto.getReportDate(), "yyyy-MM-dd"),dto.getPlanStartTime());
                        			//检查是否 是 计划结束 后
                        			ModelPlan modelPlans = factoryService.getmodelPlan(detailDto.getModelPlanId());//获取结束时间
                        			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                        			String endDate1 = sdf1.format(modelPlans.getPlanEndTime());
                        			String newDate1 = sdf1.format(new Date());
                        			Map<String, Object> maps2 = new HashMap<String, Object>();
                        			maps2.put("modelPlanId", detailDto.getModelPlanId().toString());
                        			maps2.put("recordDate", newDate1);
                        			ProgressRecordVo pv = progressViewDao.queryIsSubmitRecord(maps2);
                        			if(null != pv){
                        				item.setAccPre(pv.getAccPre());
                        			}
                        			//判断当前时间是否大于计划结束时间
                        			//如果大于，计划比例为100
                        			if (DateUtil.middate(newDate1, endDate1, sdf1) >= 0) {
                        				item.setPlanPro("100");
                        			} else {
                        				DecimalFormat df1 = new DecimalFormat("#");
                        				item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));
                        				if(100/(double)dto.getPlanTotalTime()*day<=100){
                        					item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));
                        				}else{
                        					item.setPlanPro("100");
                        				}
                        			}
                        			break;
                                }
                        	}else{
                        		Map<String, String> maps = new HashMap<String, String>();
                        		Map<String, Object> maps2 = new HashMap<String, Object>();
                        		maps.put("modelPlanId", detailDto.getModelPlanId().toString());
                    			maps.put("currentPro", detailDto.getPlanProgress());
                    			ProgressDto dto = factoryService.getPlanStartTimeByProcessNameTwo(maps);
                    			long day = DateUtil.getDayByDateSubraction(DateUtil.convertStringToDate(detailDto.getReportDate(), "yyyy-MM-dd"),dto.getPlanStartTime());
                    			//检查是否 是 计划结束 后
                    			ModelPlan modelPlans = factoryService.getmodelPlan(detailDto.getModelPlanId());//获取结束时间
                    			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                    			String endDate1 = sdf1.format(modelPlans.getPlanEndTime());
                    			String newDate1 = sdf1.format(new Date());
                    			maps2.put("modelPlanId", detailDto.getModelPlanId().toString());
                    			maps2.put("recordDate", newDate1);
                    			ProgressRecordVo pv = progressViewDao.queryIsSubmitRecord(maps2);
                    			if(null != pv){
                    				item.setAccPre(pv.getAccPre());
                    			}
                    			//判断当前时间是否大于计划结束时间
                    			//如果大于，计划比例为100
                    			if (DateUtil.middate(newDate1, endDate1, sdf1) >= 0) {
                    				item.setPlanPro("100");
                    			} else {
                    				DecimalFormat df1 = new DecimalFormat("#");
                    				if(100/(double)dto.getPlanTotalTime()*day<=100){
                    					item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));
                    				}else{
                    					item.setPlanPro("100");
                    				}
                    			}
                    			break;
                        	}
                        }else{
                        	Map<String, String> maps = new HashMap<String, String>();
                    		maps.put("modelPlanId", detailDto.getModelPlanId().toString());
                			maps.put("currentPro", detailDto.getPlanProgress());
                			ProgressDto dto = factoryService.getPlanStartTimeByProcessNameTwo(maps);
                			long day = DateUtil.getDayByDateSubraction(DateUtil.convertStringToDate(detailDto.getReportDate(), "yyyy-MM-dd"),dto.getPlanStartTime());
                			//检查是否 是 计划结束 后
                			ModelPlan modelPlans = factoryService.getmodelPlan(detailDto.getModelPlanId());//获取结束时间
                			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                			String endDate1 = sdf1.format(modelPlans.getPlanEndTime());
                			String newDate1 = sdf1.format(new Date());
                			//判断当前时间是否大于计划结束时间
                			//如果大于，计划比例为100
                			if (DateUtil.middate(newDate1, endDate1, sdf1) >= 0) {
                				item.setPlanPro("100");
                			} else {
                				DecimalFormat df1 = new DecimalFormat("#");
                				item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));
                				if(100/(double)dto.getPlanTotalTime()*day<=100){
                					item.setPlanPro(df1.format(100/(double)dto.getPlanTotalTime()*day));
                				}else{
                					item.setPlanPro("100");
                				}
                			}
                			break;
                        }
                    }
                    } else {
                        item.setDays(0);
                        item.setRecordStatus("正常");
                    }
                }
                item.setDate(DateUtil.getDateString(progressRecordVo.getRecordDate(), "MM-dd"));
                item.setTime(df.format(progressRecordVo.getRecordDate()));
                //周一周三周五，厂家未提交进度的话，大屏上只显示计划比例跟进度，不沿用头一天。周二周四周六周日沿用头一天厂家提交的进度
                item.setIsWeekend(DateUtil.dateToWeek(df.format(progressRecordVo.getRecordDate())));

                String oDate = df.format(progressRecordVo.getRecordDate());
                long tempDate = DateUtil.middate(newDate, oDate, df);
//               当前 日期之后的都不显示 且计划比例都为0
                if (tempDate < 0) {
                    item.setRecordStatus("notShow");
                    item.setPlanPro("0");
                }
                if(!"GO2".equals(item.getPlanProgress())){
                	pvvList.add(item);
                }
            }

            modelPlanDto.setItems(pvvList);
            initDefaultItemTwo(modelPlanDto, startDate, endDate,tempLastTime);
            sortList(modelPlanDto.getItems());
            //已完成工序
            List<CompleteProcessDto> cpList = new ArrayList<>();
//            List<ProcessDto> processList = progressViewDao.queryCompleteProcess(modelPlanDto.getModelPlanId());
            String processName = progressViewDao.queryModelProcessNameByPlanId(modelPlanDto.getModelPlanId());
            List<ProcessDto> processList = new ArrayList<ProcessDto>();
            if(StringUtils.isNotEmpty(processName)){
            	Map<String, Object> cMap = new HashMap<String, Object>();
            	cMap.put("processName", processName);
            	cMap.put("modelPlanId", modelPlanDto.getModelPlanId());
            	processList = progressViewDao.queryCompleteProcessName(cMap);
            }
            for (ProcessDto processDto : processList) {
                CompleteProcessDto cp = new CompleteProcessDto();
                Map<String, Object> delayMap = new HashMap<String, Object>();
                /*Map<String, Object> advanceMap = new HashMap<String, Object>();*/
                delayMap.put("modelPlanId", modelPlanDto.getModelPlanId());
                delayMap.put("processName", processDto.getModelProcessName());
                ProgressRecordVo vo = progressViewDao.queryModelPlanDaysAndStatus(delayMap);
                /*Integer delayDay = progressViewDao.sumDelayOrAdvanceDay(delayMap);
                advanceMap.put("modelProcessId", processDto.getModelProcessId());
                advanceMap.put("status", "提前");
                Integer advanceDay = progressViewDao.sumDelayOrAdvanceDay(advanceMap);
                Integer day = 0;
                day = (advanceDay==null?0:advanceDay) - (delayDay==null?0:delayDay);*/
                cp.setProcessName(processDto.getModelProcessName());
                if(null != vo){
                	cp.setDay(vo.getDelayDays());
                	if("提前".equals(vo.getStatus())){
                		cp.setStatus("1");
                	}else if("延期".equals(vo.getStatus())){
                		cp.setStatus("2");
                	}else{
                		cp.setStatus("0");
                	}
                }else{
                	cp.setDay(0);
                    cp.setStatus("0");
                }
                
                /*if (day > 0) {
                    cp.setStatus("1");
                } else if (day < 0) {
                    cp.setStatus("2");
                } else {
                    cp.setStatus("0");
                }*/
                cpList.add(cp);
            }
            Collections.reverse(cpList);
            modelPlanDto.setCp(cpList);
        }
        PageUtils.calculate(map);
        return list;
    }

    /**
     * 初始化数据库中没有提交台帐的日历报告
     *
     * @param pvv
     * @param startDate
     * @param endDate
     */
    private void initDefaultItemTwo(ModelPlanDto pvv, Date startDate, Date endDate,boolean tempLastTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String lastDate = "";
        boolean teag = false;
        String isDelay = "";
        if (pvv.getItems() != null && pvv.getItems().size() > 0) {
            lastDate = pvv.getItems().get(0).getDate();//获取第一个时间
            isDelay = pvv.getItems().get(0).getStamp();
        }
        Date d = new Date(startDate.getTime());
        long longEndDate = endDate.getTime();
        while (d.getTime() < longEndDate) {
            ProgressViewItemVo pviv = new ProgressViewItemVo();
            pviv.setDate(DateUtil.getDateString(d, "MM-dd"));
            //周一周三周五，厂家未提交进度的话，大屏上只显示计划比例跟进度，不沿用头一天。周二周四周六周日沿用头一天厂家提交的进度
            pviv.setIsWeekend(DateUtil.dateToWeek(df.format(d)));

            //计划时间后 标志
            if (lastDate.equals(DateUtil.getDateString(d, "MM-dd"))&& "isDelay".equals(isDelay)) {
                teag = true;
            }
            if (teag) {
                pviv.setStamp("isDelay");
            }
            if (!pvv.getItems().contains(pviv)) {
                pvv.getItems().add(pviv);
            }
            d = DateUtil.addDate(d, 1);
        }
        //计划结束后走这里
        if (tempLastTime) {
            String planProgress= null;//计划进度
            String planPro= null;//计划完成比例
            String currentPro = null;//当前进度
            String accPro = null;//实际完成比例
            String recordStatus = null; //记录的状态
            String progress = null; //当前进度
            Integer days = 0; //状态量级
            String ntime = df.format(new Date());

            for (ProgressViewItemVo itemVo : pvv.getItems()) {
                String nowDate = DateUtil.getDateString(new Date(), "MM-dd");
                //判断是否是今天 并且没有提交进度 赋值头一天记录
                if (nowDate.equals(itemVo.getDate()) && !"0".equals(itemVo.getLastTime())) {
                    itemVo.setPlanProgress(planProgress);
                    itemVo.setPlanPro(planPro);
                    itemVo.setCurrentPro(currentPro);
                    itemVo.setAccPro(accPro);
                    itemVo.setStamp("isDelay");
                    itemVo.setRecordStatus(recordStatus);
                    itemVo.setProgress(progress);
                    itemVo.setDays(days);
                    break;
                }
                //获取前一天的数据
                if (!StringUtil.isNullOrBlock(itemVo.getTime())) {
                    if(DateUtil.middate(ntime, itemVo.getTime(), df)==1){
                        planProgress = itemVo.getPlanProgress();
                        planPro = itemVo.getPlanPro();
                        currentPro = itemVo.getCurrentPro();
                        accPro = itemVo.getAccPro();
                        recordStatus = itemVo.getRecordStatus();
                        progress = itemVo.getProgress();
                        days = itemVo.getDays();
                    }
                }
            }
        }
    }

}
